package com.yazi.mxz.common.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.myframework.smhj.common.tool.DateUtil;
import com.myframework.smhj.hibernate.dao.BasicService;
import com.myframework.smhj.hibernate.dao.Dao;
import com.yazi.mxz.common.db.dao.RegionDao;
import com.yazi.mxz.common.entity.ValueFactory;
import com.yazi.mxz.common.entity.beans.Region;
import com.yazi.mxz.common.service.RegionService;

@Service("regionService")
public class RegionServiceImpl extends BasicService<Region> implements RegionService {
	private static Logger log = LoggerFactory.getLogger(RegionServiceImpl.class);
	
	@Resource
	RegionDao regionDao;

	@Override
	protected Dao<Region> getDao() {
		return regionDao;
	}
	
	@Override
	public Region add(Region region) {
		log.debug("add：parentId={}, type={}", region.getParentId(), region.getType());
		region = ValueFactory.validate(region);
		region.setRegionId(null);
		return regionDao.persist(region);
	}

	@Override
	public Region edit(Region region) {
		log.debug("modify：regionId={}", region.getRegionId());
		Region oldRegion = regionDao.get(region.getRegionId());
		
		// 防止篡改以下信息
		region.setRegionId(null);
		region.setParentId(null);
		region.setUpdateTime(DateUtil.getTimeStamp()); // 更新时间
		ValueFactory.combine(region, oldRegion);
		
		return regionDao.merge(oldRegion);
	}

	@Override
	public void remove(long regionId) {
		log.debug("remove：regionId={}", regionId);
		Region region = regionDao.get(regionId);
		if (null == region) {
			return;
		}
		// regionForSearch
		Region region4s = new Region();
		region4s.setParentId(regionId);
		List<Region> sonList = regionDao.listByExample(region4s);
		for (Region son : sonList) {
			remove(son.getRegionId());
		}
		regionDao.delete(region);
	}

}
